#!/bin/sh

CFLAGS=""

while getopts h:b:o:cSEgO: o
do
    case "$o" in
        h)   host="${OPTARG}";;
        b)   build="${OPTARG}";;
        o)   output="-o ${OPTARG}";;
        c)   mode=-c;;
        S)   mode=-S;;
        E)   mode=-E;;
        O)   CFLAGS="$CFLAGS -O${OPTARG}";;
        g)   CFLAGS="$CFLAGS -g";;
        [?]) echo >&2 "Usage: $0 [-h <host>] [-b <build>] [-c | -S | -E] [-o <output_file>] <input_file>" && exit 1;;
    esac
done
shift $((${OPTIND}-1))

# CLANG and llc should be defined and exported in configure script
# but in case of direct call, do something not too bad
CLANG="${CLANG:-clang}"
LLC="${LLC:-llc}"

if [ "x$host" = x ]
then
    exec $CLANG $CFLAGS $mode $output $1
fi

config=`dirname $0`
build="$build"
if [ -z "$build" ]
then
    build=`$config/config.guess`
fi

if [ -z $TMPDIR ]
then
    TMPDIR=/tmp
fi
tmpdir=$TMPDIR/xclang$PPID
mkdir $tmpdir

if [ "$mode" = -c ]
then
    $CLANG $CFLAGS -target $host -c -emit-llvm -o $tmpdir/xclang.bc $@
    $LLC -mtriple=$build -o $tmpdir/xclang.s $tmpdir/xclang.bc
    exec $CLANG -target $build -c $output $tmpdir/xclang.s
fi

if [ "$mode" = -S ]
then
    $CLANG $CFLAGS -target $host -c -emit-llvm -o $tmpdir/xclang.bc $@
    exec $LLC -mtriple=$build $output $tmpdir/xclang.bc
fi

if [ "$mode" = -E ]
then
    exec $CLANG $CFLAGS -E $output $1
fi

$CLANG $CFLAGS -target $host -c -emit-llvm -o $tmpdir/xclang.bc $@

# Adjust $LLC call for hard-float in case the build is that
case "$build" in
arm*gnueabihf)
   $LLC -mtriple=$build -float-abi=hard -o $tmpdir/xclang.s $tmpdir/xclang.bc;;
*)
   $LLC -mtriple=$build -o $tmpdir/xclang.s $tmpdir/xclang.bc;;
esac

exec $CLANG -target $build $output $tmpdir/xclang.s
